<template>
  <div class="quality-product-container">
    <el-table :data="tableData" stripe style="width: 1500%">
      <el-table-column prop="sid" label="编码" width="180" />
      <el-table-column prop="productName" label="名称" width="180" />
      <el-table-column prop="productStandard" label="规格" width="180" />
      <el-table-column prop="productCount" label="数量" width="180" />
      <el-table-column prop="productColor" label="颜色" width="180" />
       <el-table-column prop="inspectionStatus" label="检验状态" width="180" >
      <template v-slot="scope">
         <el-tag type="success" v-if="scope.row.inspectionStatus==false">已检验</el-tag>
        <el-tag type="success" v-else>已检验</el-tag>
      </template>
    </el-table-column>
      <el-table-column prop="productState" label="成品类型" >
        <template v-slot="scope">
          <el-tag type="success" v-if="scope.row.productState==1">成品</el-tag>
          <el-tag type="warning" v-else-if="scope.row.productState==2">半成品</el-tag>
          <el-tag type="danger" v-else>残次品</el-tag>
        </template>
      </el-table-column>
      <el-table-column  label="条形码" width="250">
        <template v-slot="scope">
          <div :ref="el => setBarcodeRef(el, scope.$index)" style="text-align: center; padding: 10px;">
            <!-- 条形码将在这里生成 -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      style="margin-top: 15px;"
      v-model:current-page="paing.PageIndex"
      v-model:page-size="paing.PageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="paing.total"
    />
    
    <!-- 扫码状态提示 -->
    <div v-if="scanningStatus" :class="['scan-status', scanningStatus.type]">
      {{ scanningStatus.message }}
    </div>
    
    <!-- 入库对话框 -->
    <el-dialog
      v-model="visibleDialog"
      title="入库信息"
      width="30%"
      @close="handleDialogClose">
      <el-form label-width="100px">
        <el-form-item label="入库数量：">
          <el-input-number 
            v-model="rukuNum"
            :min="1"
            controls-position="right"
            style="width: 100%"
            @mouseleave="handleAutoAdd" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import { APIs } from '@/Http/http';
import router from '@/router';
import JsBarcode from 'jsbarcode';
import globalScanner from '@/utils/globalScanner'; // 导入全局扫码服务
import { ElMessage } from 'element-plus';

// 扫码记录数据
const tableData = ref<any>([])
// 分页数据
const paing = reactive({
  PageIndex: 1,
  PageSize: 10,
  total: 0,
  totalCount: 1
})
// 扫描状态提示
const scanningStatus = ref<{ type: string; message: string } | null>(null);

// 新增响应式变量 - 入库对话框相关
const visibleDialog = ref(false)
const rukuNum = ref(1)
const currentScanInfo = ref<{productId: string; scanCode: string; productState: number}>({productId: '', scanCode: '', productState: 1})

// 组件挂载时加载数据并注册扫码回调
onMounted(() => {
  GetProduct();
  // 注册自定义扫码回调
  globalScanner.addCallback(customScanHandler);
})

// 组件卸载时移除扫码回调
onBeforeUnmount(() => {
  globalScanner.removeCallback(customScanHandler);
});

// 监听分页变化
watch(paing, () => {
  GetProduct();
})

// 获取产品数据
const GetProduct = () => {
  APIs.get("/api/Product/GetProduct", {
    params: { PageIndex: paing.PageIndex, PageSize: paing.PageSize }
  }).then(res => {
    tableData.value = res.data.data.data
    paing.total = res.data.data.total
    paing.totalCount = res.data.data.totalCount
    
    // 数据加载完成后，等待DOM更新然后生成所有条形码
    nextTick(() => {
      generateAllBarcodes()
    })
  })
}

// 扫码回调函数
const customScanHandler = (code: string) => {
  showScanningStatus('scanning', '扫描中...');
  
  // 查找扫描码对应的产品
  const scannedProduct = tableData.value.find((item: any) => item.sid === code);
  
  if (scannedProduct) {
    showScanningStatus('success', `扫描成功: ${scannedProduct.productName}`);
    
    // 存储当前扫码信息并显示对话框
    currentScanInfo.value = {
      productId: scannedProduct.finisheId,
      scanCode: code,
      productState: scannedProduct.productState
    }
    visibleDialog.value = true
  } else {
    // 如果本地没找到，尝试从服务器获取
    showScanningStatus('error', '未找到对应产品');
    console.log('未找到扫描码对应的产品:', code);
  }
};

// 鼠标离开数量输入框时自动添加
const handleAutoAdd = () => {
  if (!rukuNum.value) {
    ElMessage.warning('请输入入库数量')
    return
  }
  
  // 打印要传递的值
  console.log('准备跳转到仓库分配页面，传递的参数：');
  console.log('Find: ', currentScanInfo.value.productId);
  console.log('productState: ', currentScanInfo.value.productState);
  console.log('scanCode: ', currentScanInfo.value.scanCode);
  console.log('入库数量: ', rukuNum.value);
  
  // 跳转到仓库分配页面，传递产品信息和入库数量
  router.push({
    path: '/CangKuFenPei',
    query: {
      Find: currentScanInfo.value.productId,
      productState: currentScanInfo.value.productState,
      scanCode: currentScanInfo.value.scanCode,
      rukuNum: rukuNum.value
    }
  });
  
  // 关闭对话框并重置数据
  visibleDialog.value = false
  handleDialogClose()
}

// 重置对话框数据
const handleDialogClose = () => {
  rukuNum.value = 1
  currentScanInfo.value = {productId: '', scanCode: '', productState: 1}
}

// 显示扫描状态
const showScanningStatus = (type: string, message: string) => {
  scanningStatus.value = {
    type: type,
    message: message
  };
  
  // 3秒后清除状态提示
  setTimeout(() => {
    scanningStatus.value = null;
  }, 3000);
};

// 条形码生成相关代码
const barcodeRefs = ref<{ [key: number]: HTMLElement | null }>({})

const setBarcodeRef = (el: any, index: number) => {
  if (el) {
    barcodeRefs.value[index] = el as HTMLElement
  }
}

const generateBarcode = (code: string, index: number) => {
  const targetElement = barcodeRefs.value[index]
  if (targetElement && code) {
    targetElement.innerHTML = '';
    const canvas = document.createElement('canvas');
    targetElement.appendChild(canvas);
    JsBarcode(canvas, code, {
      format: "CODE128",
      width: 1.5,
      height: 60,
      displayValue: true,
      fontSize: 12,
      margin: 5
    });
  }
}

const generateAllBarcodes = () => {
  tableData.value.forEach((item: any, index: number) => {
    if (item.sid) {
      setTimeout(() => {
        generateBarcode(item.sid, index)
      }, 100 * index)
    }
  })
}
</script>

<style scoped>
.quality-product-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.scan-status {
  position: fixed;
  top: 50px;
  right: 20px;
  font-size: 16px;
  padding: 10px 20px;
  border-radius: 4px;
  z-index: 9999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.scan-status.scanning {
  color: #1677ff;
  background-color: #e6f4ff;
}

.scan-status.success {
  color: #52c41a;
  background-color: #f6ffed;
}

.scan-status.error {
  color: #ff4d4f;
  background-color: #fff2f0;
}
</style>
